package com.cyou.fz173.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

/**
 * <p>Title: JSON工具类</p>
 * <p>Description: 提供Json格式字符串与对象之间的相互转化</p>
 * <p>Modify: 2011-01-13</p>
 * @author 林通
 */
public final class JacksonUtil {
	
    // 全局对象映射（线程安全）
	private static final ObjectMapper mapper = new ObjectMapper();

	// 不可创建本类实例
    private JacksonUtil() {}
    
    static {
    	mapper.getSerializationConfig().setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));  
    }
    
	/**
	 * 采用JSON格式输出结果对象
	 * @param result 结果对象
	 * @throws IOException
	 */
	public static void writeJson(HttpServletResponse response, Object result) throws IOException {
		response.setContentType("text/plain; charset=UTF-8");
		PrintWriter writer = response.getWriter();
    	String json = toJson(result);
    	writer.println(json);
	}

    
    /**
     * 将对象转化为Json格式字符串
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
    	try {
    		return mapper.writeValueAsString(obj);
    	} 
    	catch (Exception ex) {
			return "{}";
		}
    }
    
    /**
     * 将Json格式字符串转化为对象
     * @param <T>
     * @param json
     * @param requiredType
     * @return
     */
    public static <T> T toObject(String json, Class<T> requiredType) {
    	try {
    		return mapper.readValue(json, requiredType);
    	} 
    	catch (Exception ex) {
			return null;
		}
    }
    
    /**
     * 将Json格式字符串转化为数组
     * @param <T>
     * @param json
     * @param requiredType
     * @return
     */
    public static <T> T[] toArray(String json, Class<T> elementType) {
    	try {
    		return mapper.readValue(json, TypeFactory.arrayType(elementType));
    	} 
    	catch (Exception ex) {
			return null;
		}
    }
    
    /**
     * 将Json格式字符串转化为集合
     * @param <T>
     * @param json
     * @param requiredType
     * @return
     */
    public static <C extends Collection<T>, T> C toCollection(String json, Class<C> collectionType, Class<T> elementType) {
    	try {
    		return mapper.readValue(json, TypeFactory.collectionType(collectionType, elementType));
    	} 
    	catch (Exception ex) {
			return null;
		}
    }
    
    /**
     * 将Json格式字符串转化为映射
     * @param <T>
     * @param json
     * @param requiredType
     * @return
     */
    @SuppressWarnings("rawtypes")
	public static <K, V> Map<K, V> toMap(String json, Class<? extends Map> mapType, Class<K> keyType, Class<V> valueType) {
    	try {
    		return mapper.readValue(json, TypeFactory.mapType(mapType, keyType, valueType));
    	} 
    	catch (Exception ex) {
			return null;
		}
    }
    
}
